package orders

import (
	"api/internal/svc"
	"api/internal/types"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
	"user_srv/userclient"
)

type MAliPayOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMAliPayOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MAliPayOrderLogic {
	return &MAliPayOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MAliPayOrderLogic) MAliPayOrder(w http.ResponseWriter, r *http.Request) (resp *types.MAliPayOrderResponse, err error) {
	fmt.Println("支付宝回调处理")
	fmt.Println(r)
	fmt.Println("支付宝回调处理")

	ouTtradeNo := r.FormValue("out_trade_no")
	tradeStatus := r.FormValue("trade_status")

	fmt.Println(ouTtradeNo, tradeStatus)

	//0待支付，1已支付，2支付失败，3已完成
	if tradeStatus == "TRADE_SUCCESS" {
		// 支付成功，更新订单状态 rpc out_trade_no trade_status
		// todo: 更新订单状态
		l.svcCtx.UserRpc.MemberStatusUpdate(l.ctx, &userclient.MemberStatusUpdateRequest{
			OrderSn: ouTtradeNo,
			Status:  1,
		})
	} else if tradeStatus == "TRADE_CLOSED" {
		// 支付失败，更新订单状态
		// todo: 更新订单状态
		l.svcCtx.UserRpc.MemberStatusUpdate(l.ctx, &userclient.MemberStatusUpdateRequest{
			OrderSn: ouTtradeNo,
			Status:  2,
		})
	} else if tradeStatus == "TRADE_FINISHED" {
		// 支付失败，更新订单状态
		// todo: 更新订单状态
		l.svcCtx.UserRpc.MemberStatusUpdate(l.ctx, &userclient.MemberStatusUpdateRequest{
			OrderSn: ouTtradeNo,
			Status:  3,
		})
	} else if tradeStatus == "WAIT_BUYER_PAY" {
		return
	}
	w.Write([]byte("success"))
	return

}
